package com.youease.chris.control
{
	import com.youease.chris.manager.GlobalObject;
	import com.youease.chris.manager.TexturesManager;
	import com.youease.chris.model.proxy.ProjectDataProxy;
	import com.youease.chris.model.vo.BigImageData;
	import com.youease.chris.model.vo.LayerData;
	import com.youease.chris.model.vo.MapData;
	import com.youease.chris.model.vo.ProjectData;
	import com.youease.chris.model.vo.TextureData;
	import com.youease.chris.model.vo.TileData;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	public class SaveProjectCommand extends SimpleCommand implements ICommand
	{
		public static const SAVE_PROJECT:String = "save_project";
		public static const CHECK_PROJECT:String = "check_project";
		private var projectDataProxy:ProjectDataProxy;
		
		public function SaveProjectCommand()
		{
			super();
		}
		
		override public function execute(notification:INotification):void {
			projectDataProxy = this.facade.retrieveProxy(ProjectDataProxy.NAME) as ProjectDataProxy;
			switch(notification.getType()) {
				case CHECK_PROJECT:
					checkProject();
					break;
				default:
				saveMapDat();
//				saveProjectAsXml();
				saveProjectAsObj();
				saveTexturesAsXml();
			}
			
		}
		
		private function checkProject():void {
			for each(var mapData:MapData in this.projectDataProxy.projectData.maps) {
				for each(var layerData:LayerData in mapData.layers) {
					for each(var tileData:TileData in layerData.tiles) {
						var texture:TextureData = TexturesManager.textures[tileData.textrue.img];
						if(texture==null) {
							Alert.show("地图还有没填充完整的地块..."+"("+tileData.gridX+","+tileData.gridY+")");
							return;
						}
					}
				}
			}
			Alert.show("已经全部编辑完成");
		}
		/**
		 * {0: {0: {0: 3, 1: 0, 2: 99}
		 * 前面两个是坐标。  括号里面 0：地形   1：可建啥   2:图片编号
		 */
		private function saveMapDat():void {
			var content:String = "{";
			for each(var mapData:MapData in this.projectDataProxy.projectData.maps) {
				for each(var layerData:LayerData in mapData.layers) {
					var sortedLayerData:Vector.<TileData> = layerData.tiles.sort(compare);
					var i:int = 0;
					for each(var tileData:TileData in sortedLayerData) {
						var texture:TextureData = tileData.textrue;
//						trace(tileData.gridX+"---"+tileData.gridY+"---"+texture.img+"---"+texture.type);
						if(i==0) {
							content += (tileData.gridX+": {"+tileData.gridY+": {0: "+texture.type+",1: "+(texture.type>7?0:1)+",2: "+texture.index+"},");
							i++;
						}else if(i<mapData.mapCols-1) {
							content += (tileData.gridY+": {0: "+texture.type+",1: "+(texture.type>7?0:1)+",2: "+texture.index+"},");
							i++;
						}else {
							content += (tileData.gridY+": {0: "+texture.type+",1: "+(texture.type>7?0:1)+",2: "+texture.index+"}},");
							i=0;
						}
					}
				}
			}
			content = content.substr(0,content.length-1)+"}";
			saveAsXml(content,2);
		}
		
		private function compare(tile1:TileData,tile2:TileData):Number {
			var num:Number = 0;
			if(tile1.gridX>tile2.gridX) {
				num = 1;
			}else if(tile1.gridX == tile2.gridX) {
				if(tile1.gridY>tile2.gridY) {
					num = 1;
				}else {
					num = -1; 
				}
			}else {
				num = -1;
			}
			return num;
		}
		
		public function saveProjectAsXml():void {
			trace(this.projectDataProxy.projectData.name);
			var content:String = "<?xml version='1.0' encoding='utf-8'?>\n";
			content += "<project name='"+this.projectDataProxy.projectData.name+"'>\n";
			content += "  <maps>\n";
			for each(var mapData:MapData in this.projectDataProxy.projectData.maps) {
				content += "    <map name='"+mapData.name+"' type='"+mapData.type+"' rows='"+mapData.mapRows+"' cols='"+mapData.mapCols+"' tileWidth='"+mapData.tileWidth+"' tileHeight='"+mapData.tileHeight+"'>\n";
				content += "      <layers>\n";
				for each(var layerData:LayerData in mapData.layers) {
					content += "        <layer name='"+layerData.name+"' depth='"+layerData.depth+"'>\n";
					for each(var tileData:TileData in layerData.tiles) {
						var texture:TextureData = tileData.textrue;
						content += "          <tile type='"+texture.type+"' gridX='"+tileData.gridX+"' gridY='"+tileData.gridY+"' img='"+texture.img+"'/>\n";
					}
					content += "        </layer>\n";
				}
				content += "      </layers>\n";
				content += "      <crossDatas>\n";
				for(var s:String in mapData.crossData) {
					var arr:Array = s.split(",");
					content += "        <crossData gridX='"+arr[0]+"' gridY='"+arr[1]+"' cross='"+(mapData.crossData[s]?1:0)+"'/>\n"
				}
				content += "      </crossDatas>\n";
				content +="    </map>\n";
			}
			content += "  </maps>\n";
			content += "</project>";
			
			saveAsXml(content);
		}
		
		private function saveProjectAsObj():void {
			var serializeTxt:String = new String();
			var projectData:ProjectData = this.projectDataProxy.projectData;
			
			var bytes:ByteArray = new ByteArray();
			bytes.writeObject(projectData);
			trace(bytes.length);
			bytes.compress();
			trace(bytes.length+"..................serializeLength");
			for(var i:uint = 0;i<bytes.length;i ++){
				serializeTxt+=(bytes[i].toString()+"-");
			}
			if(serializeTxt.length>0){
				serializeTxt = serializeTxt.substring(0,serializeTxt.length-1);
			}
			
			saveAsXml(serializeTxt);
		}
		
		public function saveTexturesAsXml():void {
			var content:String = "<?xml version='1.0' encoding='utf-8'?>\n";
			content += "<Textures>\n";
			for each(var texture:TextureData in TexturesManager.textures) {
				content += "\t<texture img='"+texture.img+"' type='"+texture.type+"' big='"+texture.big+"'/>\n";
			}
			
			content += "\t<bigs>\n"
			for each(var bigTexture:BigImageData in TexturesManager.bigTextures) {
				content += "\t\t<texture img='"+bigTexture.name+"' width='"+bigTexture.width+"' height='"+bigTexture.height+"'/>\n";
			}
			content += "\t</bigs>\n";
			
			content += "</Textures>";
			
			saveAsXml(content,0);
		}
		
		private function saveAsXml(content:String,type:int=1):void {
			try {
				var dir:String = GlobalObject.projectDir+"\\"+projectDataProxy.projectData.name;
				switch(type) {
					case 0:
						dir += ".textures";
						break;
					case 1:
						dir += ".mapProj";
						break;
					case 2:
						dir += ".dat";
						break;
				}
				var fr:File = new File(dir);
				var fs:FileStream = new FileStream();
				fs.open(fr,FileMode.WRITE);
				fs.writeUTFBytes(content);
				fs.close();
				if(type==1)
					Alert.show("保存成功");
			}catch(err:Error) {
				Alert.show("写入工程出错");
			}
		}
		
		public function saveProject():void {
			trace(this.projectDataProxy.projectData.name);
			for each(var mapData:MapData in this.projectDataProxy.projectData.maps) {
				for each(var layerData:LayerData in mapData.layers) {
					for each(var tileData:TileData in layerData.tiles) {
						var texture:TextureData = tileData.textrue;
						trace(tileData.gridX+"---"+tileData.gridY+"---"+texture.img+"---"+texture.type);
					}
				}
			}
			Alert.show("保存成功");
		}
	}
}